package chances.epg.user.event;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import chances.epg.entity.user.ScheduleOrder;
import chances.epg.user.service.ScheduleOrderService;

@Service
@EnableScheduling
public class ScheduleEventPublisher implements ApplicationEventPublisherAware {
	
	private ApplicationEventPublisher applicationEventPublisher;
	
	@Autowired
	private ScheduleOrderService repository;
	
	private List<Long> subscrList = new ArrayList<Long>();

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.applicationEventPublisher = applicationEventPublisher;
	} 

	public void publish(ScheduleOrder subscription) {
		ScheduleEvent event = new ScheduleEvent(subscription);
		this.applicationEventPublisher.publishEvent(event);
	}
	
	@Scheduled(fixedRate = 60000)
	public void checkPlayingSubscr() {
		List<ScheduleOrder> list = repository.listPlayingScheduleOrder();
		for (ScheduleOrder sOrder : list) {
			publish(sOrder);
			subscrList.add(sOrder.getSubId());
		}
		updateStatus();
	}
	
	private void updateStatus() {
		if(subscrList.size() > 0) {
			repository.updateListScheduleOrder(subscrList);
		}
		subscrList.clear();
	}
	
} 
